package com.dsp.week11.rest;

import com.dsp.week11.service.Publisher;
import com.dsp.week11.utils.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Slf4j
@RestController
public class RedisTestController {

    @Resource
    private Publisher publisher;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发布订阅测试
     */
    @GetMapping("/pub")
    public String sendMsg(@RequestParam("msg") String msg){
        publisher.pubMsg(msg);
        return "发送成功！";
    }

    /**
     * 锁测试，通过注解方式
     */
    @GetMapping(value = "/lock")
    @RedisLock(lockKey = "lock::test",lockTime = 100L,tryCount = 2,tryTime = 2)
    public String testLock() {
        log.info(Thread.currentThread().getName()+"抢到锁，返回成功");
        return "success";
    }

    /**
     * 取得锁后操作库存
     */
    @GetMapping(value = "/inventory")
    @RedisLock(lockKey = "count",lockTime = 100L,tryCount = 2,tryTime = 2)
    public Long inventoryAdd() {
        return stringRedisTemplate.opsForValue().increment("inventory",1L);
    }

    @GetMapping(value = "/lock1")
    public String testLock1() {
        return stringRedisTemplate.opsForValue().get("lock::test");
    }

}
